<template>
  <div class="login-box">
    <div class="header">
      <h3 class="brand">
        <a href="https://www.qingbaomofang.com" title target="_blank">品牌舆情</a>
        <span>专业监控平台</span>
      </h3>
    </div>
    <div class="login-bg"></div>
    <div class="login-centent" :style="right">
      <h3 class="welcome">登录情报魔方</h3>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="0px" class="login-form">
        <el-form-item prop="phone">
          <el-input size="small" v-model="ruleForm.phone" prefix-icon="el-icon-user-solid" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input size="small" v-model="ruleForm.password" type="password" prefix-icon="el-icon-lock" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item prop="imageCode">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-input size="small" v-model="ruleForm.imageCode" placeholder="请输入验证码"></el-input>
            </el-col>
            <el-col :span="12">
              <a href="javascript:;" @click="getImg" class="imgCode" title="点击刷新验证码">
                <img :src="imgSrc" alt="图片验证码" />
              </a>
            </el-col>
          </el-row>
        </el-form-item>
        <div style="clear:both;"></div>
        <!-- <div class="error-box">{{errorText}}</div> -->
        <el-form-item class="clearfix info">
          <el-checkbox class="left" v-model="ruleForm.remember">记住我</el-checkbox>
          <a class="right forget" href="javascript:;" @click="forget">忘记密码</a>
        </el-form-item>
        <el-form-item style="margin-bottom:0;">
          <el-button size="small" type="dark" class="block" @click="submitForm('ruleForm')">登录</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="footer">
      © Copyright © 2018 糖豆兄弟（北京）科技有限公司 京ICP备17042143号-3
    </div>
  </div>
</template>
<script>
import md5 from 'js-md5';
import { mapActions } from 'vuex';
import Utils from '@/utils';

export default {
  name: 'Login',
  data() {
    return {
      errorText: '',
      imgSrc: '',
      ruleForm: {
        uuid: '',
        phone: '',
        password: '',
        imageCode: '',
        remember: false
      },
      rules: {
        phone: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: '请输入正确的手机号码'
          }
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        imageCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
      }
    };
  },
  computed: {
    right() {
      return { right: (document.body.clientWidth / 1920) * 332 + 'px' };
    }
  },
  methods: {
    ...mapActions({
      storeUser: 'user/storeUser',
      storeSuser: 'user/storeSuser'
    }),
    /**
     * 登录
     */
    async signIn() {
      this.errorText = '';
      const params = {
        uuid: this.ruleForm.uuid,
        phone: this.ruleForm.phone,
        password: md5(this.ruleForm.password),
        imageCode: this.ruleForm.imageCode
      };

      const res = await this.$http.post({ map: 'LOGIN', url: 'signIn' }, params);

      console.log(res);

      const { data } = res;
      if (data['success']) {
        // 保存token
        const token = res['headers']['x-authtoken'] || res['headers']['X-AuthToken'] || null;
        window.localStorage.setItem('token', token);
        this.$http.setHeaders({ 'x-authtoken': token });
        this.storeSuser(data.data);

        // 保存登陆信息remember
        this.rememberFun();

        // 获取权限路由
        this.$store.dispatch('user/storeUserPath');

        // 保存user到vuex
        this.storeUser()
          .then(res => {
            // 展示动画
            document.getElementById('nb-global-spinner').style.display = 'block';
            // 登陆跳转
            if (this.$route.query.redirect) {
              this.$router.push(this.$route.query.redirect);
            } else {
              // 跳转
              this.$router.push({ name: 'dashboard-market' });
            }
          })
          .catch(err => {
            this.getImg();
            this.ruleForm.imageCode = '';
            // 如果账号未开通权限
            window.localStorage.removeItem('token');
            if (!err['success']) {
              this.$message({
                type: 'error',
                message: err['msg']
              });
            }
          });
      } else {
        this.getImg();
        this.ruleForm.imageCode = '';
        this.errorText = data['msg'];
        this.$message({
          type: 'error',
          message: data['msg']
        });
      }
    },
    /**
     * 获取图片验证码
     */
    getImg() {
      this.ruleForm.uuid = Utils.getUUID();
      this.imgSrc = process.env.VUE_APP_BASE_URL + '/authority/user/signImageCode?uuid=' + this.ruleForm.uuid;
    },
    /**
     * 表单提交
     */
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.signIn();
          return false;
        }
        return false;
      });
    },
    /**
     * 保存用户登录信息
     */
    rememberFun() {
      if (this.ruleForm.remember) {
        const form = {
          phone: this.ruleForm.phone,
          password: this.ruleForm.password,
          remember: this.ruleForm.remember
        };

        window.localStorage.setItem('logre', btoa(encodeURIComponent(JSON.stringify(form))));
      } else {
        window.localStorage.removeItem('logre');
      }
    },
    /**
     * 忘记密码
     */
    forget() {
      this.$router.push({ name: 'forget' });
    }
  },
  // created() {
  //   if (window.localStorage.getItem('qbmfsaas')) {
  //     window.location.reload();
  //   }
  // },
  mounted() {
    // 清空token和用户本地数据
    window.localStorage.removeItem('token');
    window.localStorage.removeItem('qbmfsaas');

    // 初始化用户登录信息
    let data = window.localStorage.getItem('logre');
    if (data) {
      data = JSON.parse(decodeURIComponent(atob(data)));
      Object.assign(this.ruleForm, data);
    }

    this.getImg();
  }
};
</script>

<style lang="less" scoped>
@base: 100rem;

@line-height: 0.4rem;
@topHeight: 80 / @base;
.login-box {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 2;

  .header {
    .brand {
      height: @topHeight;
      line-height: @topHeight;
      padding-left: @topHeight;

      a {
        font-size: 30 / @base;
        color: #333;
        font-weight: 600;
        text-decoration: none;
      }
      span {
        display: inline-block;
        line-height: @topHeight;
        padding-left: 46 / @base;
        font-size: 16 / @base;
        font-weight: 400;
        position: relative;
        &::before {
          content: '';
          position: absolute;
          left: 23 / @base;
          top: 30 / @base;
          z-index: 8;
          width: 2 / @base;
          height: 20 / @base;
          background: rgba(211, 211, 211, 1);
        }
      }
    }
  }
  .login-bg {
    position: absolute;
    left: 0;
    right: 0;
    top: @topHeight;
    bottom: 62 / @base;
    z-index: 3;
    background: url('http://candy-image.oss-cn-hangzhou.aliyuncs.com/qbmf-saas/login-bg.JPG') top center no-repeat;
    background-size: 100%;
  }
  .login-centent {
    position: absolute;
    right: 332 / @base;
    top: 0;
    bottom: 0;
    z-index: 9;
    margin: auto;
    background: #fff;
    border-radius: 8 / @base;
    width: 450 / @base;
    height: 530 / @base;
    padding: 31 / @base 74 / @base 65 / @base 76 / @base;
    box-sizing: border-box;
    box-shadow: 0 0.2rem 1.2rem 0 rgba(0, 0, 0, 0.1);

    .welcome {
      text-align: left;
      font-size: 18 / @base;
      line-height: 64 / @base;
      font-size: 24 / @base;
      font-weight: 600;
      color: #1e344d;
    }
    .login-form {
      .el-form-item {
        margin: 0;
        margin-top: 28 / @base;
        height: @line-height;
        line-height: @line-height;
        .el-form-item__content {
          height: @line-height;
          line-height: @line-height;
          box-sizing: border-box;
        }
        .el-input__inner {
          height: @line-height;
          line-height: 28 / @base;
          padding-bottom: 6 / @base;
          padding-top: 6 / @base;
          font-size: 16 / @base;
          box-sizing: border-box;
        }
        .el-input__icon {
          line-height: 1;
        }

        .el-input--prefix .el-input__inner {
          padding-left: 40 / @base;
        }
      }
      .imgCode {
        display: block;
        height: @line-height;
        line-height: @line-height;
        img {
          width: 100%;
          height: 100%;
          display: inline-block;
        }
      }
      .block {
        width: 100%;
        font-size: 16 / @base;
        font-weight: 400;
      }
      .forget {
        text-decoration: none;
        color: #69c;
        font-size: 0.12rem;
      }
      .error-box {
        margin: 0;
        padding: 0;
        padding-left: 6 / @base;
        color: red;
        font-size: 12 / @base;
        text-align: left;
        margin-top: 20 / @base;
        // line-height: 3rem;
      }
      .el-form-item__error {
        font-size: 12 / @base;
      }
      .info {
        color: #999;
        font-size: 14 / @base;
        a,
        .left {
          color: #999;
          font-size: 14 / @base;
        }
        a:hover {
          color: #1e344d;
          text-decoration: underline;
        }
      }
    }
  }
  .footer {
    position: absolute;
    bottom: 0;
    left: 0;
    z-index: 9;
    width: 100%;
    height: 62 / @base;
    line-height: 62 / @base;
    color: #565656;
    text-align: center;
    font-size: 16 / @base;
  }
}
</style>
